/*
 * Copyright (C) 2004, Velocityme Partnership
 * VelocitymeLoginActions.java
 *
 * Created on 20 December 2004, 05:50
 */

package com.velocityme.www.interfaces;

import com.velocityme.session.KeyLocal;
import com.velocityme.session.ServerConfigurationLocal;
import com.velocityme.session.SetupLocal;
import com.velocityme.www.actionforms.LoginActionForm;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.NoSuchEJBException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.actions.DispatchAction;

/**
 *
 * @author  Robert
 */
public class VelocitymeLoginActions extends DispatchAction {
    
    public ActionForward welcome(ActionMapping mapping, 
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        ServerConfigurationLocal serverConfigurationLocal = lookupServerConfigurationBean();
        session.setAttribute("owner", serverConfigurationLocal.getOwnerOrganisation());
        session.setAttribute("ownerUrl", serverConfigurationLocal.getOwnerOrganisationURL());
        SetupLocal setup = lookupSetupBean();
        if (setup.isLicenceInstalled()) {
            session.setAttribute("clientGUID", serverConfigurationLocal.getClientGUID());
            KeyLocal key = null;
            try {
                key = (KeyLocal)session.getAttribute("sessionKey");
            }
            catch(ClassCastException e) {
                // this means that we are not currently logged in so ensure that we do
                key = null;
            }
            if (key != null) {
                try {
                    if (key.isValid())
                        return mapping.findForward("ACTION_HOME");
                    else
                        session.removeAttribute("sessionKey");
                } catch(NoSuchEJBException ex) {
                    session.removeAttribute("sessionKey");
                }
            }
            return mapping.findForward("ACTION_LOGIN");
        }
        else {
            session.setAttribute("clientGUID", serverConfigurationLocal.getClientGUID());
            return mapping.findForward("ACTION_ADD_LICENCE");
        }
    }
    
    public ActionForward login(ActionMapping mapping, 
                               ActionForm form,
                               HttpServletRequest request,
                               HttpServletResponse response) throws Exception {
        LoginActionForm loginAF = (LoginActionForm)form;
        HttpSession session = request.getSession();
        KeyLocal key = lookupKeyBean();
        ActionErrors errors = new ActionErrors();
        switch (key.login(loginAF.getUsername(), loginAF.getPassword(), request.getRemoteHost())) {
            case SUCCESS:
                // now set up the required attributes
                session.setAttribute("sessionKey", key);
                session.removeAttribute("markedNodeID");
                Long nodeID = (Long)session.getAttribute("nodeID");
                if (nodeID == null)
                    return mapping.findForward("ACTION_HOME");
                else {
                    request.setAttribute("nodeID", nodeID);
                    return mapping.findForward("ACTION_NODE");
                }
            case NO_AVAILABLE_LICENCE:
                errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.login.no.available.licence"));
                break;
            case INCORRECT_PASSWORD:
                errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.login.incorrect.password"));
                break;
            case INVALID_USER:
                errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.login.invalid.username"));
                break;
            case UNKNOWN_USER:
                errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.login.unknown.username"));
                break;
            default:
            case ERROR:
                errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.login.error"));
                break;
        }
        session.removeAttribute("sessionKey");
        saveErrors(request, errors);
        return mapping.findForward("ACTION_FAILED");
    }

    public ActionForward invalidKey(ActionMapping mapping, 
                                    ActionForm form,
                                    HttpServletRequest request,
                                    HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        session.removeAttribute("sessionKey");
        ActionErrors errors = new ActionErrors();
        errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.invalid.key"));
        saveErrors(request, errors);
        return mapping.findForward("ACTION_LOGIN");
    }

    private SetupLocal lookupSetupBean() {
        try {
            Context c = new InitialContext();
            return (SetupLocal) c.lookup("java:comp/env/SetupBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private KeyLocal lookupKeyBean() {
        try {
            Context c = new InitialContext();
            return (KeyLocal) c.lookup("java:comp/env/KeyBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    private ServerConfigurationLocal lookupServerConfigurationBean() {
        try {
            Context c = new InitialContext();
            return (ServerConfigurationLocal) c.lookup("java:comp/env/ServerConfigurationBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

}
